package org.jsola.hr.common;


import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ImageUtil {
    private static final org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(ImageUtil.class);

    /**
     * 将宽度相同的图片，竖向追加在一起 ##注意：宽度必须相同
     *
     * @param picList 文件流数组
     * @param outPath 输出路径
     */
    public static void yPic(List<BufferedImage> picList, String outPath) {// 纵向处理图片
        if (picList == null || picList.size() <= 0) {
            log.info("图片数组为空!");
            return;
        }
        try {
            // 总高度
            int height = 0,
                    // 总宽度
                    width = 0,
                    // 临时的高度 , 或保存偏移高度
                    offsetHeight = 0,
                    // 临时的高度，主要保存每个高度
                    tmpHeight = 0,
                    // 图片的数量
                    picNum = picList.size();
            // 保存每个文件的高度
            int[] heightArray = new int[picNum];
            // 保存图片流
            BufferedImage buffer = null;
            // 保存所有的图片的RGB
            List<int[]> imgRgb = new ArrayList<int[]>();
            // 保存一张图片中的RGB数据
            int[] tmpImgRgb;
            for (int i = 0; i < picNum; i++) {
                buffer = picList.get(i);
                // 图片高度
                heightArray[i] = offsetHeight = buffer.getHeight();
                if (i == 0) {
                    // 图片宽度
                    width = buffer.getWidth();
                }
                // 获取总高度
                height += offsetHeight;
                // 从图片中读取RGB
                tmpImgRgb = new int[width * offsetHeight];
                tmpImgRgb = buffer.getRGB(0, 0, width, offsetHeight, tmpImgRgb, 0, width);
                imgRgb.add(tmpImgRgb);
            }
            // 设置偏移高度为0
            offsetHeight = 0;
            // 生成新图片
            BufferedImage imageResult = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
            for (int i = 0; i < picNum; i++) {
                tmpHeight = heightArray[i];
                if (i != 0) {
                    // 计算偏移高度
                    offsetHeight += tmpHeight;
                }
                // 写入流中
                imageResult.setRGB(0, offsetHeight, width, tmpHeight, imgRgb.get(i), 0, width);
            }
            File outFile = new File(outPath);
            // 写图片
            ImageIO.write(imageResult, "png", outFile);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void writeOutput(String str, File file) {
        try {
            FileOutputStream fos = new FileOutputStream(file);
            Writer out = new OutputStreamWriter(fos, "GBK");
            out.write(str);
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static String readInput(File file) {
        StringBuffer buffer = new StringBuffer();
        try {
            FileInputStream fis = new FileInputStream(file);
            InputStreamReader isr = new InputStreamReader(fis, "GBK");
            Reader in = new BufferedReader(isr);
            int i;
            while ((i = in.read()) > -1) {
                buffer.append((char) i);
            }
            in.close();
            return buffer.toString();
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }


    public static void main(String[] args) throws IOException {
        File file = new File("C:\\Users\\Think\\Desktop\\whahy.png");
        OutputStream stream = new FileOutputStream(file);
        //获取一个二维码图片
        BitMatrix bitMatrix = createCode("https://render.alipay.com/p/s/ulink/?scheme=alipays%3A%2F%2Fplatformapi%2Fstartapp%3FappId%3D2021002133661287%26appClearTop%3Dfalse%26startMultApp%3DYES%26page%3Dpages%252Fconfirm%252Findex%252Findex%253FsignParams%253Dalipay_root_cert_sn%25253D687b59193f3f462dd5336e5abf83c5d8_02941eef3187dddf3d3b83462e1dfcf6%252526alipay_sdk%25253Dalipay-sdk-java-dynamicVersionNo%252526app_auth_token%25253D202112BB5749bcededfd473da74874201849eX15%252526app_cert_sn%25253D910f4d4be21db2e75119b20c4047dc21%252526app_id%25253D2021002187615001%252526biz_content%25253D%2525257B%25252522batch_trans_id%25252522%2525253A%25252522202112149340701781%25252522%25252B%25252B%2525257D%252526charset%25253DUTF-8%252526format%25253DJSON%252526method%25253Dalipay.fund.batch.app.pay%252526sign%25253DO3kV1deb2wEh5%2525252BCmeWShjDQJujgbCH%2525252BB%2525252BNeSukPj2Z1gCbsIuefg6OffIaLpSvVkW7Bjrm14VkvZEHlLKbEGQ89t5hBZ%2525252BqBC27U60sCcGyprNXdsdLw80bwPiM0TXtxGeQ3kcYo6t6fUNSO1B5HXfT74ZsCae7%2525252BisFtWYFZJwIfPqMmiINAEo%2525252FR0kJpLtf8Kmm9kQ1Q5jfjZW8I1%2525252F84If7ibvCWp8tGnoY97kQ2aWChCE%2525252FR0SMbShCY8BSGmwI54jFCuls7s9sK4ax0eg5lbxgpwg7jN1%2525252FiKEVldlVnXWrtEYHI5Rh9%2525252FJxbi1G5X1Ji50zdzs2bmuBuCGelB7%2525252Bi%2525252BEA%2525253D%2525253D%252526sign_type%25253DRSA2%252526timestamp%25253D2021-12-14%25252B20%2525253A09%2525253A56%252526version%25253D1.0");
        //以流的形式输出到前端
        MatrixToImageWriter.writeToStream(bitMatrix , "png" , stream);

    }

    /**
     *  生成二维码
     * @param content 二维码的内容
     * @return BitMatrix对象
     * */
    public static BitMatrix createCode(String content) {
        //二维码的宽高
        int width = 2000;
        int height = 2000;

        //其他参数，如字符集编码
        Map<EncodeHintType, Object> hints = new HashMap<>();
        hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
        //容错级别为L
        hints.put(EncodeHintType.ERROR_CORRECTION , ErrorCorrectionLevel.L);
        //白边的宽度，可取0~4
        hints.put(EncodeHintType.MARGIN , 0);
        BitMatrix bitMatrix = null;
        try {
            //生成矩阵，因为我的业务场景传来的是编码之后的URL，所以先解码
            bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, width, height, hints);
            //bitMatrix = deleteWhite(bitMatrix);
        } catch (WriterException e) {
            e.printStackTrace();
        }
        return bitMatrix;
    }

    /**
     *  删除生成的二维码周围的白边，根据审美决定是否删除
     * @param matrix BitMatrix对象
     * @return BitMatrix对象
     * */
    private static BitMatrix deleteWhite(BitMatrix matrix) {
        int[] rec = matrix.getEnclosingRectangle();
        int resWidth = rec[2] + 1;
        int resHeight = rec[3] + 1;

        BitMatrix resMatrix = new BitMatrix(resWidth, resHeight);
        resMatrix.clear();
        for (int i = 0; i < resWidth; i++) {
            for (int j = 0; j < resHeight; j++) {
                if (matrix.get(i + rec[0], j + rec[1])) {
                    resMatrix.set(i, j);
                }
            }
        }
        return resMatrix;
    }

}
